//
//  ProductAddView.swift
//  ptbuy
//
//  Created by MyMac on 2025/1/3.
//

import SwiftUI
import AVFoundation
import AVKit
import CoreData

struct ProductAddView: View {
    @Environment(\.managedObjectContext) private var viewContext
//    addProduct:$addProduct,clientId:$clientId,addProductStatus:$addProductStatus
    @Binding var addProduct:Bool
    @Binding var clientId:String
    @Binding var addProductStatus:Bool
    @Binding var totalProduct:Int16 //显示总商品件数
    @Binding var totalPrice:Int64//显示商品总价格
    @Binding var maxOrder:Int16//商品最大排序
    
    @State private var productName:String = ""
    @State private var productPrice:Int64 = 0
    
    
    var body: some View {
        NavigationView{
            VStack{
                Divider()
                ScrollView{
                    VStack{
                        HStack{
                            Text("名称：")
                            TextField("请输入名称", text: $productName)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.3)
                                .overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                .cornerRadius(8)
                                    )
                            
                            Text("").padding(5).frame(width: 30)
                        }
                    
                        HStack{
                            Text("价格：")
                            TextField("请输入价格", value: $productPrice,format:.number)
                                .keyboardType(.numberPad)
                                .overlay(
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color.black)
                                        .padding([.top])
                                    )
                              
                                .cornerRadius(8)
                                .multilineTextAlignment(.center)
                            Text("元").padding(5).font(.system(size: 20))
                        }
                    }.padding(20)
                    VStack{
                        //pauiz
                        photoVideoOverlayView
                    }
                }
                
                    
                Spacer()
            }.frame(maxWidth:.infinity,maxHeight: .infinity).background(
                // 创建渐变背景
                LinearGradient(
                    gradient: Gradient(
                        colors: [
                            Color("startColor").opacity(
                                10
                            ),
                            // 上半部分颜色，增加不透明度
                            Color("endColor")
                        ]// 上半部分颜色，增加不透明度
                    ),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .edgesIgnoringSafeArea(.all)  // 确保背景覆盖整个屏幕
            ).navigationBarTitle("修改照片信息", displayMode: .inline).navigationViewStyle(
                StackNavigationViewStyle()
            ) // 推荐在全屏时使用此样式
            .background(
                // 背景遮罩
                Color.black.opacity(0.5)
                    .edgesIgnoringSafeArea(.all)
                
            )
            .toolbar {
                // 修改标题字体大小
                ToolbarItem(placement: .topBarLeading) {
                    Text("返回")
                        .clipShape(
                            Capsule()
                        ) // 使用 Capsule 形状来实现圆角效果
                        .onTapGesture {
                            addProduct = false
                        }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Text("保存")
                        .clipShape(
                            Capsule()
                        ) // 使用 Capsule 形状来实现圆角效果
                        .onTapGesture {
//                            addProduct = false
                            insertProduct()
                        }
                }
            }
        }
    }
    
    
    @State var order:Int16 = 0;
    // 增加一条数据
    private func insertProduct() {
        let newProduct = Product(context: viewContext)
        newProduct.id = UUID().uuidString
            .replacingOccurrences(of: "-", with: "")// 或者其他类型，确保是唯一的标识
        newProduct.product_name = productName
        
        newProduct.product_price = productPrice
        newProduct.time = formattedDate()
        newProduct.inttime = Int64(formattedDateInt()) ?? 0
        if !medias.isEmpty{
            
            let jsonString =  Utils.convertArrayToJsonString(
                stringArray: medias
            )
            if(jsonString != ""){
                newProduct.mult = jsonString
            }
        }
       
        order = maxOrder+1
      
        newProduct.myorder = order
        newProduct.status = 1
        newProduct.pid = clientId
        
        totalProduct = totalProduct+1
        totalPrice = totalPrice+productPrice
        
        do {
            try viewContext.save()
            
            /*
             新增之后增加客户总价和总件数
             */
            modifyClient()
            
            addProduct = false
        } catch {
            addProductStatus = true
            addProduct = false
            // 处理错误
            print("Error saving context: \(error.localizedDescription)")
        }
    }
    
    /*
     修改客户信息
     */
    private func modifyClient(){
        // 查找对应的 Product
        let fetchRequest: NSFetchRequest<Client> = Client.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "id == %@", clientId)
        
        do {
            let results = try viewContext.fetch(fetchRequest)

            if let client = results.first {
                // 更新该 person 的名字
                client.total_price = totalPrice
                client.total_product = totalProduct
                try viewContext.save()  // 保存更新
            }
        } catch {
            print("更新失败：\(error.localizedDescription)")
        }
    }
    
    // 创建日期格式化器
    func formattedDateInt() -> String {
        let formatter = DateFormatter()
        // 获取当前时间
        let currentDate = Date()
        formatter.dateFormat = "yyyyMMdd"
        return formatter.string(from: currentDate)
    }
    
    // 创建日期格式化器
    func formattedDate() -> String {
        let formatter = DateFormatter()
        // 获取当前时间
        let currentDate = Date()
        formatter.dateStyle = .long
        formatter.timeStyle = .medium
        return formatter.string(from: currentDate)
    }
    
    
    
    /*
        照片视频地方
     */
    
    @State private var permissionStatus: AVAuthorizationStatus = .notDetermined
    //调用相机拍照
    @State private var isImagePickerPresented = false
    //调用相机录像
    @State private var isCameraPresented = false
    @State private var permissAlert = false  // 控制是否显示Alert
    @State private var photo:Int8 = 0//记录已有照片数
    @State private var video:Int8 = 0//记录已有视频数
    @State private var medias:[String] = [] // 图片数组，替换成你的图片名称
    @State private var type:Int8 = 0//类型；0:拍照;1:选择相册
    @State private var selectedImageIndex = 0 // 当前选中的图片索引
    @State private var isDeleteAlert = false // 当前选中的图片索引
    @State private var isDeleteVideoAlert = false // 当前选中的视频索引
    @State private var isImagePresented = false//点击图片全屏显示
    @State private var isFullScreen = false//点击视频全屏显示
    
    var photoVideoOverlayView: some View {
        VStack{
            Divider()
            HStack{
                Button(action:{
                    permissionStatus = AVCaptureDevice
                        .authorizationStatus(for: .video)
                    type=0
                    if permissionStatus == .authorized {
                        isImagePickerPresented = true
                    }else if permissionStatus == .denied {
                        permissAlert = true
                    } else {
                        requestCameraPermission()
                    }
                                        
                }){
                    Text("拍照").frame(width:50,height:8).foregroundColor(.black)
                }.alert(isPresented: $permissAlert){
                    Alert(
                        title: Text("提示"),
                        message: Text(
                            "相机权限已被拒绝，请前往设置中开启权限"
                        ),
                        primaryButton: .destructive(Text("前往设置")) {
                            permissAlert = false
                            if let settingsURL = URL(
                                string: UIApplication.openSettingsURLString
                            ) {
                                UIApplication.shared.open(settingsURL)
                            }
                        },
                        secondaryButton: .cancel(Text("关闭")) {
                            permissAlert = false
                        })
                }.sheet(isPresented: $isImagePickerPresented) {
                    ImagePicker(isImagePickerPresented: $isImagePickerPresented,
                                medias:$medias,
                                type:$type,
                                photo:$photo)
                }.padding()
                    .foregroundColor(.black)
                    .background(Color("btn")).opacity(0.8)
                    .cornerRadius(8)
                Spacer()
                Button(action:{
                    isCameraPresented = true
                }){
                    Text("录像").frame(width:50,height:8).foregroundColor(.black)
                }.sheet(isPresented: $isCameraPresented) {
                    VideoPicker(
                        isPresented: $isCameraPresented,
                        medias:$medias,
                        video:$video
                    )
                }.padding()
                    .foregroundColor(.black)
                    .background(Color("btn")).opacity(0.8)
                    .cornerRadius(8)
                Spacer()
                
                Button(action:{
                    type=1
                    isImagePickerPresented = true
                }){
                    Text("相册").frame(width:50,height:8).foregroundColor(.black)
                }.sheet(isPresented: $isImagePickerPresented) {
                    ImagePicker(isImagePickerPresented: $isImagePickerPresented,
                                medias:$medias,
                                type:$type,
                                photo:$photo)
                }.padding()
                    .foregroundColor(.black)
                    .background(Color("btn")).opacity(0.8)
                    .cornerRadius(8)
                Spacer()
            }.padding()
            Text("已有：照片：\(photo)张；视频：\(video)个")
                .multilineTextAlignment(.leading)
                .padding(.horizontal, 10)
            TabView (selection: $selectedImageIndex){

                ForEach(0..<medias.count, id: \.self) { index in
                    if(
                        medias[index]
                            .contains(".mov") ||  medias[index]
                            .contains(".MOV")
                    ){
                        VStack{
                            HStack{
                                Text("")
                                Spacer()
                                Image("shanchu") // 这里不需要加文件扩展名
                                    .resizable()   // 使图片可调整大小
                                    .scaledToFit() // 保持图片比例
                                    .frame(width: 25, height: 25) // 设置图片的尺寸
                                    .padding([.top,.trailing],8)
                                    .onTapGesture(){
                                        isDeleteVideoAlert = true
                                    }.alert(
                                        "确定删除此视频吗？",
                                        isPresented:$isDeleteVideoAlert
                                    ){
                                        Button("关闭", role: .cancel) {
                                            isDeleteVideoAlert = false
                                        }
                                        Button("删除", role: .destructive) {
                                            
                                            medias.remove(at: selectedImageIndex)
                                                video -= 1
                                            isDeleteVideoAlert = false
                                        }
                                    }
                            }
                            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                medias[index]
                            )
                            
                            let player = AVPlayer(
                                url: URL(fileURLWithPath: filename.path)
                            );
                            VideoPlayer(player: player)
                                .onTapGesture {
                                    // 点击时，进入全屏模式
                                    isFullScreen = true
                                }.onAppear {
                                    // 在视图显示时播放视频
                                    player.pause()
                                }.fullScreenCover(
                                    isPresented:$isFullScreen
                                ){
                                    let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                        medias[selectedImageIndex]
                                    )
                
                                    let player = AVPlayer(
                                        url: URL(
                                            fileURLWithPath: filename.path
                                        )
                                    );
                                    // 全屏播放视频
                                    VideoPlayer(player: player)
                                        .edgesIgnoringSafeArea(
                                            .all
                                        ) // 使视频全屏
                                        .onTapGesture() {
                                            // 点击时，进入全屏模式
                                            isFullScreen = false
                                            player.pause()
                                        }.onAppear {
                                            // 在视图显示时播放视频
                                            player.play()
                                        }
                                }

                        }
                    }else{
                        let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                            medias[index]
                        )
                        if let uiImage = UIImage(
                            contentsOfFile: filename.path
                        ) {
                            
                            VStack{
                                HStack{
                                    Text("")
                                    Spacer()
                                    Image("shanchu") // 这里不需要加文件扩展名
                                        .resizable()   // 使图片可调整大小
                                        .scaledToFit() // 保持图片比例
                                        .frame(
                                            width: 25,
                                            height: 25
                                        ) // 设置图片的尺寸
                                        .padding([.top,.trailing],8)
                                        .onTapGesture(){
                                            isDeleteAlert = true
                                        }.alert(
                                            "确定删除此照片吗？",
                                            isPresented:$isDeleteAlert
                                        ){
                                            Button("关闭", role: .cancel) {
                                                isDeleteAlert = false
                                            }
                                            Button( "删除",role: .destructive ) {
                                                medias.remove(at: selectedImageIndex)
                                                    photo -= 1
                                                isDeleteAlert = false
                                            }
                                        }
                                }
                               
                                
                                // 从文件路径加载图片
                                Image(uiImage: uiImage)
                                    .resizable()  // 使图片可调整大小
                                    .scaledToFit()  // 保持比例缩放
                                    .frame(
                                        width: UIScreen.main.bounds.width,
                                        height: 300
                                    )
                                // 设置显示尺寸
                                    .padding()
                                    .onTapGesture {
                                        // 点击图片时，显示大图
                                        isImagePresented = true
                                    }.fullScreenCover(
                                        isPresented: $isImagePresented
                                    ) {
                                        let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                            medias[selectedImageIndex]
                                        )
                                        if let uiImage = UIImage(
                                            contentsOfFile: filename.path
                                        ) {
                                            // 显示大图的视图
                                            Image(
                                                uiImage: uiImage
                                            ) // 用你的图片名称替换
                                            .resizable()
                                            .scaledToFit()
                                            .edgesIgnoringSafeArea(.all)
                                            .onTapGesture {
                                                // 点击大图时关闭
                                                isImagePresented.toggle()
                                            }
                                        }
                                      
                                    }
                            }
                            
                            

                        } else {
                            Text("File not found")
                                .foregroundColor(.red)
                        }
                    }
                   
                }
            }.tabViewStyle(
                PageTabViewStyle(indexDisplayMode: .always)
            )// 启用分页样式
            .frame(height: 350) // 设定图片视图的高度
            .background(Color(.white))
            .padding()
            Spacer()
        }
    }
    
    
    func requestCameraPermission() {
        AVCaptureDevice.requestAccess(for: .video) { response in
            DispatchQueue.main.async {
                permissionStatus = AVCaptureDevice
                    .authorizationStatus(for: .video)
            }
        }
    }
}

